import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, Row, Col, Spin } from 'antd';
import { WeaDialog, WeaSearchGroup, WeaUpload, WeaTools, WeaInput, WeaInputNumber, WeaDatePicker, WeaError } from "ecCom";
import { RenderForm, FormatDate, onCloseHandle } from '../../util';

const { viewer } = WeaTools;
@inject('groupListStore')
@observer
export default class NewGroupVoting extends Component {
  constructor(props) {
    super(props);
    this.classPrefix = `${props.prefixCls}-new` || 'group-voting-list-new';
  }

  onCancel = () => {
    const { groupListStore, groupListStore: { newGroupVotingStore } } = this.props;
    const { setStoreState } = groupListStore;
    setStoreState({newVisible: false});
    newGroupVotingStore.newGroupVoteForm.resetForm();
    newGroupVotingStore.clearNewVote();
  }

  getForm = (form, fields) => {
    const { isFormInit } = form;
    const { checkmode } = form.getFormParams();
    let group = [];
    isFormInit && fields && fields.map(c => {
      let items = [];
      c.items.map(field => {
        if (field.domkey[0] === 'themepic') {
          items.push({ com: RenderForm(form, field, '', this.renderUpload(), '', true) })
        } else if (field.domkey[0] === 'checkmode') {
          if (checkmode === '1') {
            items.push({ com: RenderForm(form, field, '', this.renderMode()) })
          } else {
            items.push({ com: RenderForm(form, field) })
          }
        } else if (field.domkey[0] === 'maxvoteoption') {

        } else if (field.domkey[0] === 'voteoption') {
          items.push({ com: RenderForm(form, field, '', this.renderVoteOpts(), '', true) })
        } else if (field.domkey[0] === 'votesec') {
          items.push({ com: RenderForm(form, field, '', <span className='tip'>(只有发布者才可查看投票人统计)</span>, '') })
        } else if (field.domkey[0] === 'voteendtime') {
          items.push({ com: RenderForm(form, field, '', this.renderEndDate(), '', true) })
        } else {
          items.push({ com: RenderForm(form, field) })
        }
      })
      group.push(<WeaSearchGroup col={1} needTigger={true} showGroup={c.defaultshow} items={items}/>)
    })
    return group;
  }

  /* 主题图片 */
  renderUpload = () => {
    const { groupListStore: { newGroupVotingStore } } = this.props;
    const { themeImage, setStoreState } = newGroupVotingStore;
    if (toJS(themeImage).length > 0) {
      const { imgSrc, fileid } = toJS(themeImage)[0];
      return (
        <div className={`${this.classPrefix}-themeImg`}>
          <img 
            data-imgsrc={imgSrc} 
            ref={fileid} 
            src={imgSrc} 
            className="formImgPlay"
            onClick={viewer}
          />
          <i className="icon-coms-Clear" onClick={() => setStoreState({themeImage: []})} />
        </div>
      )
    }
    return (
      <WeaUpload
        btnSize="small"
        uploadUrl="/api/groupchatvote/upload/uploadImgForGroupLoad"
        category="string"  // 文件上传目录
        isDetail
        multiSelection={false}
        maxFilesNumber={1}
        limitType={'jpg,gif,png,jpeg'}
        onChange={(ids, list) => setStoreState({themeImage: list})}
        className={`${this.classPrefix}-uploadImg`}
      />
    )
  }

  /* 选择模式 */
  renderMode = () => {
    const { groupListStore: { newGroupVotingStore } } = this.props;
    const { maxvoteoption, setStoreState } = newGroupVotingStore;
    return (
      <span className={`${this.classPrefix}-inputNum`}>
        最多
        <WeaInputNumber 
          className='input'
          min={2} 
          defaultValue={1} 
          value={maxvoteoption} 
          onChange={v => setStoreState({maxvoteoption: v})}
        />项
      </span>
    )
  }

  /* 投票选项 */
  renderVoteOpts = () => {
    const { groupListStore: { newGroupVotingStore } } = this.props;
    const { voteOptions } = newGroupVotingStore;
    return (
      <div className={`${this.classPrefix}-voteOptions`}>
        {
          toJS(voteOptions) && Object.keys(toJS(voteOptions)).map(key => {
            return this.renderOptionItem(toJS(voteOptions)[key], key > 2)
          })
        }
        <a onClick={e => this.addOption(e)}>添加选项</a>
      </div>
    )
  }

  renderOptionItem = (data, isExtra = false) => {
    const { groupListStore: { newGroupVotingStore } } = this.props;
    const { onOptImageChange, voteOptions, deleteOptImg, onOptContentChange } = newGroupVotingStore;
    const judgeOpts = toJS(voteOptions) && toJS(voteOptions[data.key]);
    let item = [
      <Row className={`${this.classPrefix}-voteOptions-item`}>
        <Col span={19}>
          <WeaError tipPosition='bottom' ref={`optInpt${data.key}`} error='投票选项未填写'>
            <WeaInput
              viewAttr={3}
              placeholder={`选项${data.key}`}
              value={judgeOpts && toJS(voteOptions[data.key].content) || ''}
              onChange={v => onOptContentChange(v, data)}
            />
          </WeaError>
        </Col>
        <Col span={3} className='addImage'>
          <WeaUpload
            btnSize="small"
            uploadUrl="/api/groupchatvote/upload/uploadImgForGroupLoad"
            category="string"  // 文件上传目录
            limitType={'jpg,gif,png,jpeg'}
            onChange={(ids, list) => onOptImageChange(ids, list, data)}
          >
            <i className="icon-portal-photo-o" />
          </WeaUpload>
        </Col>
        { isExtra && <Col span={2}><i className="icon-coms02-Delete" onClick={() => this.deleteOption(data.key)} /></Col> }
      </Row>
    ];
    if (judgeOpts && toJS(voteOptions[data.key].imageArr) && toJS(voteOptions[data.key].imageArr).length > 0) {
      let renderImage = toJS(voteOptions[data.key].imageArr).map(item => {
        const {fileid, imgSrc} = item;
        return (
          <div className={`${this.classPrefix}-voteOptions-optionImg-item`} key={fileid}>
            <img 
              data-imgsrc={imgSrc} 
              ref={fileid} 
              src={imgSrc} 
              className="formImgPlay"
              onClick={viewer}
            />
            <i className="icon-coms-Clear" onClick={() => deleteOptImg(fileid, data)} />
          </div>
        )
      })
      item.push(<div className={`${this.classPrefix}-voteOptions-optionImg`}>{renderImage}</div>)
    }
    return item
  }

  /* 投票截止时间 */
  renderEndDate = () => {
    const { groupListStore: { newGroupVotingStore } } = this.props;
    const { finishTime, setStoreState } = newGroupVotingStore;
    let nowTime = FormatDate(new Date, 'yyyy-MM-dd HH:mm');
    let dayTime = new Date().getDate();
    let hourTime = new Date().getHours();
    let secondTime = new Date().getMinutes();
    return (
      <WeaError tipPosition='bottom' ref='datePick' error="截止时间为空">
        <WeaDatePicker
          showTime={{ format: "HH:mm" }}
          format="yyyy-MM-dd HH:mm"
          needSecond
          startValue={nowTime}
          value={finishTime}
          onChange={v => setStoreState({finishTime: v})}
          viewAttr={3}
          disabledTimeConfig={{
            dayConfig: {
              [dayTime]: {
                disabledHour: this.range(0, hourTime),
                HourConfig: {
                  [hourTime]: {
                    disabledMinute: this.range(0, secondTime),
                    minuteConfig: {
                      [secondTime]: [11]
                    }
                  }
                }
              }
            }
          }}
        />
      </WeaError>
    )
  }

  range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }

  /* 添加选项 */
  addOption = (e) => {
    e.preventDefault();
    const { groupListStore: { newGroupVotingStore } } = this.props;
    const { voteOptions, setStoreState } = newGroupVotingStore;
    const optArr = Object.keys(toJS(voteOptions));
    const objectKey = Number(optArr[optArr.length-1]) + 1;
    setStoreState({voteOptions: {...voteOptions, [objectKey]: {key: objectKey, imageArr: []} }})
  }

  /* 删除选项 */
  deleteOption = (option) => {
    const { groupListStore: { newGroupVotingStore } } = this.props;
    const { voteOptions, setStoreState } = newGroupVotingStore;
    let newOptions = toJS(voteOptions);
    delete newOptions[option];
    setStoreState({voteOptions: newOptions});
  }

  publishVote = () => {
    const { groupListStore: { newGroupVotingStore, setStoreState, getGroupVoteList, groupid, isgroup, viewGroupVote, listStore } } = this.props;
    const { voteOptions, publishVote, finishTime } = newGroupVotingStore;
    if (finishTime === '') {
      this.refs.datePick.showError();
      return;
    }
    for(let v in toJS(voteOptions)) {
      if (!(toJS(voteOptions)[v].content) || toJS(voteOptions)[v].content === '') {
        this.refs[`optInpt${v}`].showError();
        return;
      }
    }

    let params = { isgroup, groupid };
    publishVote(params, (funRes) => {
      getGroupVoteList('', true, () => {listStore.tableUpdate({showCheck: false})});
      setStoreState({newVisible: false, isShowDetail: true, voteId: funRes.groupChatAdd.votingid});
      viewGroupVote({votingid: funRes.groupChatAdd.votingid});
      this.onCancel();
      if (window.em) {
        em.sendMsg({
          targetId: '', // 消息会话ID
          msgType: 10, // 消息类型：1-文本 2-链接 10-E6分享消息
          msgInfo: {
            content: funRes.groupChatAdd.votetheme, // 分享标题（必填）
            desc: `截止时间： ${funRes.groupChatAdd.enddate} ${funRes.groupChatAdd.endtime}`, // 分享描述（非必填）
            canforward: 0, // 消息是否允许转发 1：是（默认） 0：否
            sharetypename: "群投票", //消息类型显示标题，没有则按sharetype显示
            sharetypeicon: 'http://i1.sinaimg.cn/ent/d/2008-06-04/U105P28T3D2048907F326DT20080604225106.jpg', //消息类型显示图标
            sharetypebgcolor: '#9999FF', //消息类型背景颜色，没有则按sharetype显示
            // showimage: 'http://i1.sinaimg.cn/ent/d/2008-06-04/U105P28T3D2048907F326DT20080604225106.jpg', //消息显示图片地址，没有则不显示图片
            showimage: funRes.groupChatAdd.themeimagesrc, //消息显示图片地址，没有则不显示图片
            linkurl: `/spa/smallApp/static/index.html#/main/groupVoting/groupVotingList?id=${funRes.groupChatAdd.votingid}`, // 消息链接地址（必填）
            // sharetype: '', // 分享数据类型,值有"doc","workflow","task","pdoc","folder" ,"crm" 分别代表文档，流程，任务，云盘文档，云盘文件，客户名片
            // shareid: funRes.votingid, // 分享的数据ID（必填）
            opentype_pc: 1,//PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
          },
          success: (res) => {
            // console.log('success',res)
          },
          fail: (res) => {
            // console.log('fail',res)
          },
        });
      }
    });
  }
  
  render() {
    const { groupListStore: { newVisible, newGroupVotingStore } } = this.props;
    const { newGroupVoteForm, newGroupVoteFields, newGroupVoteLoading } = newGroupVotingStore;
    const buttons = [
      <Button type="primary" onClick={this.publishVote}>发布</Button>,
      <Button onClick={this.onCancel}>取消</Button>
    ]
    return (
      <WeaDialog
        title={'发起新投票'}
        icon='icon-portal-reportform'
        className={this.classPrefix}
        visible={newVisible}
        style={{ width: 700, height: 600 }}
        buttons={buttons}
        onCancel={this.onCancel}
        hasScroll
      >
        <Spin spinning={newGroupVoteLoading}>
          { this.getForm(newGroupVoteForm, toJS(newGroupVoteFields)) }
        </Spin>
      </WeaDialog>
    )
  }
}
